package com.GamersCom.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.GamersCom.db.User;
import com.GamersCom.model.MgrFactory;
import com.GamersCom.model.UserMgr;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String nextView = "login.jsp";
		RequestDispatcher rd = request.getRequestDispatcher(nextView);
		rd.forward(request, response);		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//retrieve session from request
		HttpSession session = (HttpSession) request.getSession();
		String nextView;
		MgrFactory factory = (MgrFactory) this.getServletContext().getAttribute("mgrFactory");
		UserMgr userMgr = factory.getUserMgr();
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		User user = userMgr.getApprovedUser(username, password);  
		
		if (user != null ) //valid user
		{
			session.setAttribute("username",username);
			session.setAttribute("accesslevel", user.getAccessLevel());		
			nextView = "/index.jsp";
		} else {
			String msg = "Username and password do not match or you do not have an account yet.";
			request.setAttribute("error", msg);
			nextView = "login.jsp";			
		}
				
		RequestDispatcher rd = request.getRequestDispatcher(nextView);
		rd.forward(request, response);	
				
	}

}
